import { Entity } from '../systems/EntitySystem.js';
import { RenderSystem } from '../systems/RenderSystem.js';
import { GameConfig, DefenseSystemType } from '../config/GameConfig.js';
import { Missile } from './Missile.js';
import { Interceptor } from './Interceptor.js';
import { Poolable } from '../systems/PerformanceOptimizationSystem.js';

export enum DefenseState {
    IDLE = 'idle',
    SCANNING = 'scanning',
    TARGETING = 'targeting',
    FIRING = 'firing',
    RELOADING = 'reloading'
}

export enum TargetPriority {
    DISTANCE = 'distance',
    THREAT_LEVEL = 'threat_level',
    SPEED = 'speed',
    HEALTH = 'health'
}

export class DefenseSystem implements Entity, Poolable {
    public id: string;
    public x: number;
    public y: number;
    public width: number = 40;
    public height: number = 40;
    public active: boolean = true;
    
    private systemType: DefenseSystemType;
    private config: any;
    private health: number;
    private maxHealth: number;
    private range: number = 0;
    private accuracy: number = 0;
    private fireRate: number = 0;
    private cost: number;
    private maintenanceCost: number;
    
    private state: DefenseState = DefenseState.IDLE;
    private currentTarget: Missile | null = null;
    private cooldownTimer: number = 0;
    private scanAngle: number = 0;
    private interceptors: Interceptor[] = [];
    private targetPriority: TargetPriority = TargetPriority.THREAT_LEVEL;
    private debugTimer: number = 0; // 调试计时器
    
    // 🚀 新增：发射视觉效果
    private muzzleFlashTimer: number = 0; // 炮口闪光计时器
    private muzzleFlashDuration: number = 200; // 闪光持续时间(ms)
    private lastShotAngle: number = 0; // 最后发射角度
    private launchEffectParticles: Array<{
        x: number;
        y: number;
        vx: number;
        vy: number;
        life: number;
        maxLife: number;
        size: number;
    }> = []; // 发射粒子效果
    
    // 地形加成
    private terrainBonus: { range: number; accuracy: number } = { range: 1.0, accuracy: 1.0 };

    constructor(id: string, systemType: DefenseSystemType, gridX: number, gridY: number) {
        this.id = id;
        this.systemType = systemType;
        this.config = GameConfig.DEFENSE_SYSTEMS[systemType];
        this.health = 100;
        this.maxHealth = 100;
        this.cost = this.config.cost;
        this.maintenanceCost = this.config.maintenance;
        
        // 设置性能参数
        this.setupPerformanceConfig();
        
        // 计算在防御区域中的实际位置
        const defenseAreaStartX = GameConfig.IRAN_AREA_WIDTH + GameConfig.SEA_AREA_WIDTH;
        this.x = defenseAreaStartX + gridX * GameConfig.DEFENSE_GRID_SIZE + GameConfig.DEFENSE_GRID_SIZE / 2;
        this.y = gridY * GameConfig.DEFENSE_GRID_SIZE + GameConfig.DEFENSE_GRID_SIZE / 2;
        
        // 根据位置计算地形加成
        this.calculateTerrainBonus(gridX, gridY);
    }

    private setupPerformanceConfig(): void {
        const baseConfig = this.config;
        
        if (Array.isArray(baseConfig.range)) {
            this.range = baseConfig.range[0]; // 基础射程
        } else {
            this.range = baseConfig.range;
        }
        
        if (Array.isArray(baseConfig.accuracy)) {
            this.accuracy = baseConfig.accuracy[0]; // 基础精度
        } else {
            this.accuracy = baseConfig.accuracy || 90;
        }
        
        this.fireRate = baseConfig.cooldown || 2000;
        
        // 🔧 强制日志确认初始配置
        console.log(`🛡️ ${this.config.name || this.systemType} 性能配置:`);
        console.log(`   基础射程: ${this.range}px`);
        console.log(`   基础精度: ${this.accuracy}%`);
        console.log(`   开火间隔: ${this.fireRate}ms`);
    }

    private calculateTerrainBonus(gridX: number, gridY: number): void {
        // 简单的地形系统：后排有高度优势
        if (gridX >= 3) { // 后排
            this.terrainBonus.range = 1.3;
            this.terrainBonus.accuracy = 1.15;
        } else if (gridX >= 1) { // 中排
            this.terrainBonus.range = 1.15;
            this.terrainBonus.accuracy = 1.1;
        } else { // 前排
            this.terrainBonus.range = 1.0;
            this.terrainBonus.accuracy = 1.0;
        }
        
        // 应用地形加成
        this.range *= this.terrainBonus.range;
        this.accuracy *= this.terrainBonus.accuracy;
        
        // 🔧 强制日志确认最终配置（包含地形加成）
        console.log(`🛡️ ${this.config.name || this.systemType} 最终配置（含地形加成）:`);
        console.log(`   最终射程: ${this.range.toFixed(0)}px (地形加成: ${this.terrainBonus.range}x)`);
        console.log(`   最终精度: ${this.accuracy.toFixed(0)}% (地形加成: ${this.terrainBonus.accuracy}x)`);
        console.log(`   位置: (${this.x.toFixed(0)}, ${this.y.toFixed(0)})`);
    }

    update(deltaTime: number): void {
        if (!this.active) return;

        // 更新冷却时间
        if (this.cooldownTimer > 0) {
            this.cooldownTimer -= deltaTime;
            if (this.cooldownTimer <= 0) {
                this.state = DefenseState.SCANNING;
                console.log(`🔄 ${this.getSystemName()} 冷却完成，重新开始扫描`);
            }
        }

        // 更新扫描角度（视觉效果）
        this.scanAngle += deltaTime * 0.002;
        if (this.scanAngle > Math.PI * 2) {
            this.scanAngle = 0;
        }

        // 更新拦截弹
        this.updateInterceptors(deltaTime);

        // 🚀 更新发射视觉效果
        this.updateLaunchEffects(deltaTime);

        // 🔧 高频状态机更新 - 每帧都检查
        this.updateStateMachine(deltaTime);
        
        // 🔧 强制扫描 - 确保不会遗漏目标
        if (this.state === DefenseState.SCANNING || this.state === DefenseState.IDLE) {
            this.scanForTargets();
        }
        
        // 每2秒输出一次系统状态（调试）
        this.debugTimer += deltaTime;
        if (this.debugTimer >= 2000 && GameConfig.DEBUG.ENABLED) {
            const entitySystem = (globalThis as any).gameEngine?.entitySystem;
            const allMissiles = entitySystem?.getAllEntities().filter((entity: any) => 
                entity.constructor.name === 'Missile' && entity.active
            ) || [];
            
            if (allMissiles.length > 0) {
                console.log(`🛡️ ${this.getSystemName()}: 状态=${this.state}, 射程=${this.range}px, 导弹数=${allMissiles.length}, 冷却=${this.cooldownTimer.toFixed(0)}ms`);
            }
            this.debugTimer = 0;
        }
    }

    private updateStateMachine(deltaTime: number): void {
        switch (this.state) {
            case DefenseState.IDLE:
                // 立即开始扫描
                this.state = DefenseState.SCANNING;
                break;
                
            case DefenseState.SCANNING:
                // 扫描在update主循环中处理
                break;
                
            case DefenseState.TARGETING:
                if (this.currentTarget && this.currentTarget.active && this.isTargetInRange(this.currentTarget)) {
                    // 🔧 立即发射，不等待
                    this.state = DefenseState.FIRING;
                } else {
                    // 目标失效，重新扫描
                    this.currentTarget = null;
                    this.state = DefenseState.SCANNING;
                }
                break;
                
            case DefenseState.FIRING:
                if (this.currentTarget && this.currentTarget.active && this.isTargetInRange(this.currentTarget)) {
                    // 执行发射
                    this.fireAtTarget();
                } else {
                    // 目标失效，重新扫描
                    this.currentTarget = null;
                    this.state = DefenseState.SCANNING;
                }
                break;
                
            case DefenseState.RELOADING:
                // 冷却时间由cooldownTimer控制，在主update中处理
                if (this.cooldownTimer <= 0) {
                    this.state = DefenseState.SCANNING;
                }
                break;
        }
    }

    private scanForTargets(): void {
        // 🔧 只有在非冷却状态下才扫描
        if (this.cooldownTimer > 0) {
            return;
        }

        // 从EntitySystem获取所有活跃导弹
        const entitySystem = (globalThis as any).gameEngine?.entitySystem;
        if (!entitySystem) {
            console.warn(`❌ ${this.getSystemName()}: EntitySystem不可用`);
            return;
        }
        
        const allEntities = entitySystem.getAllEntities();
        const missiles = allEntities.filter((entity: any) => 
            entity.constructor.name === 'Missile' && entity.active
        );
        
        if (missiles.length === 0) {
            this.state = DefenseState.SCANNING;
            return;
        }
        
        // 🔍 详细扫描日志（降低频率）
        if (Math.random() < 0.05) { // 5%概率输出扫描日志
            console.log(`🔍 ${this.getSystemName()} @ (${this.x.toFixed(0)}, ${this.y.toFixed(0)}) 扫描到 ${missiles.length} 枚导弹`);
            console.log(`   防御系统射程: ${this.range.toFixed(0)}px, 状态: ${this.state}`);
        }
        
        // 筛选射程内的目标
        const targetsInRange = missiles.filter((missile: any) => {
            const distance = Math.sqrt(
                Math.pow(missile.x - this.x, 2) + 
                Math.pow(missile.y - this.y, 2)
            );
            const inRange = distance <= this.range;
            
            // 🔍 重要目标的详细日志
            if (inRange && Math.random() < 0.1) { // 10%概率输出在射程内的目标
                console.log(`🎯 导弹 ${missile.id} @ (${missile.x.toFixed(0)}, ${missile.y.toFixed(0)})`);
                console.log(`   距离防御系统: ${distance.toFixed(0)}px (射程: ${this.range.toFixed(0)}px)`);
                console.log(`   ✅ 在射程内 - 准备拦截!`);
            }
            
            return inRange;
        });
        
        if (targetsInRange.length === 0) {
            this.state = DefenseState.SCANNING;
            return;
        }
        
        // 🔧 优先检查是否已有目标且仍在射程内
        if (this.currentTarget && this.isTargetInRange(this.currentTarget)) {
            // 继续跟踪当前目标
            this.state = DefenseState.TARGETING;
            return;
        }
        
        // 选择威胁最高的目标
        const bestTarget = this.selectBestTarget(targetsInRange);
        if (bestTarget) {
            this.currentTarget = bestTarget;
            this.state = DefenseState.TARGETING;
            console.log(`🎯 ${this.getSystemName()} 锁定新目标: ${bestTarget.id} @ (${bestTarget.x.toFixed(0)}, ${bestTarget.y.toFixed(0)})`);
        }
    }
    
    private getMissileClass(): any {
        // 导入Missile类的引用，避免循环依赖
        return (globalThis as any).MissileClass;
    }
    
    private selectBestTarget(missiles: any[]): any {
        // 按威胁等级排序：距离近、速度快、伤害高的优先
        return missiles.sort((a, b) => {
            const distanceA = Math.sqrt(Math.pow(a.x - this.x, 2) + Math.pow(a.y - this.y, 2));
            const distanceB = Math.sqrt(Math.pow(b.x - this.x, 2) + Math.pow(b.y - this.y, 2));
            
            const speedA = Math.sqrt(a.getVelocity().x ** 2 + a.getVelocity().y ** 2);
            const speedB = Math.sqrt(b.getVelocity().x ** 2 + b.getVelocity().y ** 2);
            
            const threatA = a.getDamage() + speedA * 2 - distanceA * 0.1;
            const threatB = b.getDamage() + speedB * 2 - distanceB * 0.1;
            
            return threatB - threatA; // 高威胁优先
        })[0];
    }

    private isTargetInRange(target: Missile): boolean {
        const distance = Math.sqrt(
            Math.pow(target.x - this.x, 2) + 
            Math.pow(target.y - this.y, 2)
        );
        return distance <= this.range;
    }

    private fireAtTarget(): void {
        if (!this.currentTarget) return;

        // 🚀 强制日志确认发射
        console.log(`🔥🔥🔥 ${this.getSystemName()} 正在发射拦截弹! 🔥🔥🔥`);
        console.log(`   目标: ${this.currentTarget.id}`);
        console.log(`   防御系统位置: (${this.x.toFixed(0)}, ${this.y.toFixed(0)})`);
        console.log(`   目标位置: (${this.currentTarget.x.toFixed(0)}, ${this.currentTarget.y.toFixed(0)})`);

        // 🎯 计算真实发射位置（发射管/发射口位置）
        const launchPosition = this.calculateLaunchPosition();
        console.log(`   计算发射点: (${launchPosition.x.toFixed(0)}, ${launchPosition.y.toFixed(0)})`);

        // 创建拦截弹
        const interceptor = new Interceptor(
            `interceptor_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
            this.systemType,
            launchPosition.x,
            launchPosition.y,
            this.currentTarget,
            this.accuracy
        );
        
        this.interceptors.push(interceptor);
        
        // 🚀 强制添加到EntitySystem并验证
        const entitySystem = (globalThis as any).gameEngine?.entitySystem;
        if (entitySystem) {
            entitySystem.addEntity(interceptor);
            console.log(`🚀🚀🚀 拦截弹 ${interceptor.id} 已强制添加到EntitySystem`);
            console.log(`   拦截器初始位置: (${interceptor.x.toFixed(0)}, ${interceptor.y.toFixed(0)})`);
            console.log(`   拦截器是否活跃: ${interceptor.active}`);
            console.log(`   拦截器目标: ${interceptor.target?.id}`);
            
            // 🚀 触发发射视觉效果
            this.triggerLaunchEffects();
            
            // 🔍 立即验证拦截器是否在EntitySystem中
            setTimeout(() => {
                const foundInterceptor = entitySystem.getEntity(interceptor.id);
                const allEntities = entitySystem.getAllEntities();
                const interceptorCount = allEntities.filter((e: any) => e.constructor.name === 'Interceptor').length;
                
                console.log(`🔍 验证结果:`);
                console.log(`   EntitySystem总实体数: ${allEntities.length}`);
                console.log(`   拦截器总数: ${interceptorCount}`);
                console.log(`   目标拦截器存在: ${foundInterceptor ? '✅ 是' : '❌ 否'}`);
                
                if (!foundInterceptor) {
                    console.error(`❌❌❌ 拦截器 ${interceptor.id} 未在EntitySystem中找到! 这是BUG!`);
                }
            }, 100);
        } else {
            console.error(`❌❌❌ EntitySystem不可用! 无法发射拦截弹!`);
        }
        
        // 进入冷却状态
        this.state = DefenseState.RELOADING;
        this.cooldownTimer = this.fireRate;
        this.currentTarget = null;
        
        console.log(`⏱️ ${this.getSystemName()} 进入冷却状态，冷却时间: ${this.fireRate}ms`);
    }

    /**
     * 计算拦截弹的准确发射位置
     * 根据防御系统类型和目标方向调整发射点
     */
    private calculateLaunchPosition(): { x: number; y: number } {
        // 🎯 基础发射位置就是防御系统的中心位置
        let launchX = this.x;
        let launchY = this.y;
        
        // 根据系统类型调整发射偏移
        switch (this.systemType) {
            case 'IRON_DOME':
                // 铁穹系统：从顶部略微偏移发射
                launchY -= 15; // 向上偏移15像素
                break;
                
            case 'ARROW_3':
                // 箭-3系统：从中心位置发射大型导弹
                launchY -= 20; // 向上偏移20像素
                break;
                
            case 'GREEN_PINE_RADAR':
                // 雷达系统不发射导弹，但如果万一调用了...
                launchY -= 10;
                break;
                
            default:
                // 默认从中心稍上方发射
                launchY -= 12;
        }
        
        // 如果有目标，可以根据目标方向微调发射位置
        if (this.currentTarget) {
            const dx = this.currentTarget.x - this.x;
            const dy = this.currentTarget.y - this.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            
            if (distance > 0) {
                // 朝目标方向稍微偏移发射点（模拟发射管转向）
                const dirX = dx / distance;
                const dirY = dy / distance;
                
                // 轻微向目标方向偏移发射位置
                launchX += dirX * 8; // 8像素的偏移
                launchY += dirY * 8;
            }
        }
        
        console.log(`🚀 ${this.getSystemName()} 计算发射位置:`);
        console.log(`   防御系统位置: (${this.x}, ${this.y})`);
        console.log(`   网格位置推算: gridX=${Math.floor((this.x - (GameConfig.IRAN_AREA_WIDTH + GameConfig.SEA_AREA_WIDTH)) / GameConfig.DEFENSE_GRID_SIZE)}, gridY=${Math.floor(this.y / GameConfig.DEFENSE_GRID_SIZE)}`);
        console.log(`   计算发射位置: (${launchX.toFixed(0)}, ${launchY.toFixed(0)})`);
        console.log(`   偏移量: x=${(launchX - this.x).toFixed(0)}, y=${(launchY - this.y).toFixed(0)}`);
        
        return {
            x: launchX,
            y: launchY
        };
    }

    private updateInterceptors(deltaTime: number): void {
        for (let i = this.interceptors.length - 1; i >= 0; i--) {
            const interceptor = this.interceptors[i];
            interceptor.update(deltaTime);
            
            if (!interceptor.active) {
                this.interceptors.splice(i, 1);
            }
        }
    }

    // 🚀 新增：更新发射视觉效果
    private updateLaunchEffects(deltaTime: number): void {
        // 更新炮口闪光
        if (this.muzzleFlashTimer > 0) {
            this.muzzleFlashTimer -= deltaTime;
        }
        
        // 更新发射粒子效果
        for (let i = this.launchEffectParticles.length - 1; i >= 0; i--) {
            const particle = this.launchEffectParticles[i];
            particle.life -= deltaTime;
            
            if (particle.life <= 0) {
                this.launchEffectParticles.splice(i, 1);
                continue;
            }
            
            // 更新粒子位置
            particle.x += particle.vx * deltaTime / 1000;
            particle.y += particle.vy * deltaTime / 1000;
            
            // 重力效果
            particle.vy += 50 * deltaTime / 1000;
        }
    }

    // 🚀 新增：触发发射视觉效果
    private triggerLaunchEffects(): void {
        // 开始炮口闪光
        this.muzzleFlashTimer = this.muzzleFlashDuration;
        
        // 计算发射角度
        if (this.currentTarget) {
            const dx = this.currentTarget.x - this.x;
            const dy = this.currentTarget.y - this.y;
            this.lastShotAngle = Math.atan2(dy, dx);
        }
        
        // 创建发射粒子效果
        const particleCount = 8;
        for (let i = 0; i < particleCount; i++) {
            const angle = (Math.PI * 2 * i) / particleCount + Math.random() * 0.5;
            const speed = 50 + Math.random() * 30;
            
            this.launchEffectParticles.push({
                x: this.x,
                y: this.y - 15, // 从防御系统顶部发射
                vx: Math.cos(angle) * speed,
                vy: Math.sin(angle) * speed - 20, // 向上的初始速度
                life: 500 + Math.random() * 300,
                maxLife: 800,
                size: 2 + Math.random() * 3
            });
        }
        
        console.log(`🔥 ${this.getSystemName()} 触发发射视觉效果！`);
    }

    // 🚀 新增：渲染发射视觉效果
    private renderLaunchEffects(renderSystem: RenderSystem): void {
        const ctx = (renderSystem as any).ctx;
        
        // 渲染炮口闪光
        if (this.muzzleFlashTimer > 0) {
            const flashIntensity = this.muzzleFlashTimer / this.muzzleFlashDuration;
            const flashRadius = 25 * flashIntensity;
            
            ctx.save();
            
            // 创建闪光渐变
            const gradient = ctx.createRadialGradient(this.x, this.y - 15, 0, this.x, this.y - 15, flashRadius);
            gradient.addColorStop(0, `rgba(255, 255, 255, ${flashIntensity})`);
            gradient.addColorStop(0.3, `rgba(255, 200, 0, ${flashIntensity * 0.8})`);
            gradient.addColorStop(0.6, `rgba(255, 100, 0, ${flashIntensity * 0.6})`);
            gradient.addColorStop(1, 'rgba(255, 0, 0, 0)');
            
            ctx.fillStyle = gradient;
            ctx.beginPath();
            ctx.arc(this.x, this.y - 15, flashRadius, 0, Math.PI * 2);
            ctx.fill();
            
            // 发射方向光束
            if (this.lastShotAngle !== 0) {
                const beamLength = 40 * flashIntensity;
                const endX = this.x + Math.cos(this.lastShotAngle) * beamLength;
                const endY = this.y - 15 + Math.sin(this.lastShotAngle) * beamLength;
                
                ctx.strokeStyle = `rgba(255, 255, 255, ${flashIntensity})`;
                ctx.lineWidth = 4 * flashIntensity;
                ctx.beginPath();
                ctx.moveTo(this.x, this.y - 15);
                ctx.lineTo(endX, endY);
                ctx.stroke();
            }
            
            ctx.restore();
        }
        
        // 渲染发射粒子
        this.launchEffectParticles.forEach(particle => {
            const lifeRatio = particle.life / particle.maxLife;
            const alpha = lifeRatio;
            
            ctx.save();
            ctx.fillStyle = `rgba(255, ${100 + lifeRatio * 155}, 0, ${alpha})`;
            ctx.beginPath();
            ctx.arc(particle.x, particle.y, particle.size * lifeRatio, 0, Math.PI * 2);
            ctx.fill();
            ctx.restore();
        });
    }

    render(renderSystem: RenderSystem): void {
        if (!this.active) return;

        // 渲染射程圈（仅在选中或调试时显示）
        if (GameConfig.DEBUG.SHOW_COLLISION_BOXES) {
            this.renderRange(renderSystem);
        }

        // 渲染防御系统主体
        this.renderSystemBody(renderSystem);
        
        // 渲染状态指示器
        this.renderStatusIndicator(renderSystem);
        
        // 渲染拦截弹
        this.renderInterceptors(renderSystem);
        
        // 渲染健康条
        this.renderHealthBar(renderSystem);
        
        // 渲染系统信息（调试）
        if (GameConfig.DEBUG.ENABLED) {
            this.renderDebugInfo(renderSystem);
        }
        
        // 🚀 渲染发射视觉效果
        this.renderLaunchEffects(renderSystem);
    }

    private renderRange(renderSystem: RenderSystem): void {
        const ctx = (renderSystem as any).ctx;
        ctx.save();
        ctx.strokeStyle = 'rgba(46, 134, 171, 0.3)';
        ctx.lineWidth = 1;
        ctx.setLineDash([5, 5]);
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.range, 0, Math.PI * 2);
        ctx.stroke();
        ctx.restore();
    }

    private renderSystemBody(renderSystem: RenderSystem): void {
        const color = this.getSystemColor();
        const icon = this.getSystemIcon();
        
        // 尝试使用SVG渲染
        const svgRendered = (renderSystem as any).renderDefenseSystemWithSVG?.(
            this.systemType,
            this.x, this.y,
            this.width,
            color,
            icon
        );
        
        // 如果SVG渲染失败，使用备用渲染方案
        if (!svgRendered) {
            // 备用方案：使用几何形状和emoji
            renderSystem.renderCircleEntity(this.x, this.y, this.width / 2, color);
            
            // 渲染边框
            const ctx = (renderSystem as any).ctx;
            ctx.save();
            ctx.strokeStyle = '#ffffff';
            ctx.lineWidth = 2;
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.width / 2, 0, Math.PI * 2);
            ctx.stroke();
            ctx.restore();
            
            // 渲染系统图标
            renderSystem.renderText(icon, this.x - 8, this.y + 5, 'white', 'bold 16px Arial');
        }
        
        // 渲染扫描线（仅雷达系统）
        if (this.systemType === 'GREEN_PINE_RADAR') {
            this.renderRadarScan(renderSystem);
        }
        
        // 🚀 渲染发射光束（如果有活跃拦截弹）
        this.renderLaunchBeams(renderSystem);
    }

    private renderRadarScan(renderSystem: RenderSystem): void {
        const ctx = (renderSystem as any).ctx;
        ctx.save();
        ctx.strokeStyle = 'rgba(241, 143, 1, 0.6)';
        ctx.lineWidth = 2;
        ctx.beginPath();
        ctx.moveTo(this.x, this.y);
        const endX = this.x + Math.cos(this.scanAngle) * this.range;
        const endY = this.y + Math.sin(this.scanAngle) * this.range;
        ctx.lineTo(endX, endY);
        ctx.stroke();
        ctx.restore();
    }

    // 🚀 新增：渲染发射光束连接到拦截弹
    private renderLaunchBeams(renderSystem: RenderSystem): void {
        if (this.interceptors.length === 0) return;
        
        const ctx = (renderSystem as any).ctx;
        ctx.save();
        
        this.interceptors.forEach(interceptor => {
            if (!interceptor.active) return;
            
            // 创建光束渐变
            const gradient = ctx.createLinearGradient(this.x, this.y, interceptor.x, interceptor.y);
            gradient.addColorStop(0, this.getSystemColor()); // 防御系统颜色
            gradient.addColorStop(0.5, 'rgba(255, 255, 255, 0.8)'); // 中间亮白
            gradient.addColorStop(1, 'rgba(255, 255, 255, 0.3)'); // 拦截弹处淡化
            
            // 主光束
            ctx.strokeStyle = gradient;
            ctx.lineWidth = 3;
            ctx.lineCap = 'round';
            ctx.setLineDash([]);
            ctx.beginPath();
            ctx.moveTo(this.x, this.y);
            ctx.lineTo(interceptor.x, interceptor.y);
            ctx.stroke();
            
            // 脉冲效果
            const pulseIntensity = (Math.sin(Date.now() * 0.01) + 1) / 2;
            ctx.strokeStyle = `rgba(255, 255, 255, ${pulseIntensity * 0.6})`;
            ctx.lineWidth = 1;
            ctx.stroke();
            
            // 在防御系统处添加发射点标记
            ctx.fillStyle = this.getSystemColor();
            ctx.beginPath();
            ctx.arc(this.x, this.y, 8, 0, Math.PI * 2);
            ctx.fill();
            
            ctx.fillStyle = 'white';
            ctx.beginPath();
            ctx.arc(this.x, this.y, 4, 0, Math.PI * 2);
            ctx.fill();
        });
        
        ctx.restore();
    }

    private renderStatusIndicator(renderSystem: RenderSystem): void {
        let statusColor: string;
        let statusText: string;
        
        switch (this.state) {
            case DefenseState.IDLE:
                statusColor = '#28a745'; // 绿色
                statusText = 'IDLE';
                break;
            case DefenseState.SCANNING:
                statusColor = '#ffc107'; // 黄色
                statusText = 'SCAN';
                break;
            case DefenseState.TARGETING:
                statusColor = '#ff8c00'; // 橙色
                statusText = 'LOCK';
                break;
            case DefenseState.FIRING:
                statusColor = '#dc3545'; // 红色
                statusText = 'FIRE';
                // 🚀 发射状态时添加脉冲效果
                const pulseIntensity = (Math.sin(Date.now() * 0.02) + 1) / 2;
                statusColor = `rgba(220, 53, 69, ${0.5 + pulseIntensity * 0.5})`;
                break;
            case DefenseState.RELOADING:
                statusColor = '#6c757d'; // 灰色
                statusText = 'RELOAD';
                break;
            default:
                statusColor = '#17a2b8'; // 蓝色
                statusText = 'UNK';
        }
        
        // 状态指示器圆点
        renderSystem.renderCircleEntity(this.x + 15, this.y - 15, 4, statusColor);
        
        // 🚀 发射状态时的额外效果
        if (this.state === DefenseState.FIRING) {
            // 外围脉冲环
            const pulseRadius = 8 + Math.sin(Date.now() * 0.02) * 3;
            renderSystem.renderCircleEntity(this.x + 15, this.y - 15, pulseRadius, 'rgba(220, 53, 69, 0.3)');
            
            // 发射文本提示
            renderSystem.renderText(
                '🔥 FIRING',
                this.x - 25,
                this.y - 35,
                '#ff0000',
                'bold 12px Arial'
            );
        }
        
        // 状态文本
        renderSystem.renderText(
            statusText,
            this.x + 20,
            this.y - 20,
            statusColor,
            'bold 8px Arial'
        );
        
        // 拦截弹数量指示
        if (this.interceptors.length > 0) {
            renderSystem.renderText(
                `${this.interceptors.length} INT`,
                this.x - 30,
                this.y + 30,
                'white',
                'bold 10px Arial'
            );
        }
    }

    private renderInterceptors(renderSystem: RenderSystem): void {
        this.interceptors.forEach(interceptor => {
            interceptor.render(renderSystem);
        });
    }

    private renderHealthBar(renderSystem: RenderSystem): void {
        const barWidth = this.width;
        const barHeight = 4;
        const healthPercent = this.health / this.maxHealth;
        
        // 背景
        renderSystem.renderEntity(
            this.x, this.y - this.height/2 - 8,
            barWidth, barHeight,
            'rgba(0, 0, 0, 0.5)'
        );
        
        // 健康条
        renderSystem.renderEntity(
            this.x - barWidth/2 + (barWidth * healthPercent)/2,
            this.y - this.height/2 - 8,
            barWidth * healthPercent, barHeight,
            healthPercent > 0.5 ? '#28a745' : healthPercent > 0.2 ? '#ffc107' : '#dc3545'
        );
    }

    private renderDebugInfo(renderSystem: RenderSystem): void {
        const info = [
            `Range: ${this.range.toFixed(0)}`,
            `Acc: ${this.accuracy.toFixed(0)}%`,
            `State: ${this.state}`,
            `Interceptors: ${this.interceptors.length}`
        ];
        
        info.forEach((text, index) => {
            renderSystem.renderText(
                text,
                this.x + 25,
                this.y - 15 + index * 12,
                'white',
                '10px Arial'
            );
        });
    }

    private getSystemColor(): string {
        switch (this.systemType) {
            case 'IRON_DOME':
                return GameConfig.COLORS.ISRAEL_PRIMARY;
            case 'ARROW_3':
                return GameConfig.COLORS.ISRAEL_SECONDARY;
            case 'GREEN_PINE_RADAR':
                return GameConfig.COLORS.ISRAEL_ACCENT;
            default:
                return GameConfig.COLORS.ISRAEL_PRIMARY;
        }
    }

    private getSystemIcon(): string {
        // 返回几何图形描述而不是emoji
        switch (this.systemType) {
            case 'IRON_DOME':
                return 'ID'; // Iron Dome abbreviation
            case 'ARROW_3':
                return 'A3'; // Arrow-3 abbreviation
            case 'GREEN_PINE_RADAR':
                return 'GP'; // Green Pine abbreviation
            default:
                return '?';
        }
    }

    private getSystemName(): string {
        return this.config.name;
    }

    // 公共接口
    public setTarget(target: Missile): void {
        if (this.isTargetInRange(target) && this.state === DefenseState.SCANNING) {
            this.currentTarget = target;
            this.state = DefenseState.TARGETING;
        }
    }

    public setTargetPriority(priority: TargetPriority): void {
        this.targetPriority = priority;
    }

    public getTargetPriority(): TargetPriority {
        return this.targetPriority;
    }

    public getSystemType(): DefenseSystemType {
        return this.systemType;
    }

    public getRange(): number {
        return this.range;
    }

    public getAccuracy(): number {
        return this.accuracy;
    }

    public getCost(): number {
        return this.cost;
    }

    public getMaintenanceCost(): number {
        return this.maintenanceCost;
    }

    public isReady(): boolean {
        return this.state === DefenseState.SCANNING || this.state === DefenseState.IDLE;
    }

    public takeDamage(damage: number): void {
        this.health -= damage;
        if (this.health <= 0) {
            this.health = 0;
            this.active = false;
        }
    }

    public destroy(): void {
        this.active = false;
        
        // 🔧 清理所有拦截弹，从EntitySystem中移除
        const entitySystem = (globalThis as any).gameEngine?.entitySystem;
        this.interceptors.forEach(interceptor => {
            interceptor.destroy();
            if (entitySystem) {
                entitySystem.removeEntity(interceptor.id);
            }
        });
        this.interceptors = [];
    }

    // Poolable interface implementation
    public reset(): void {
        this.active = true;
        this.health = this.maxHealth;
        this.state = DefenseState.IDLE;
        this.currentTarget = null;
        this.scanAngle = 0;
        this.cooldownTimer = 0;
        this.interceptors = [];
    }

    public isActive(): boolean {
        return this.active;
    }

    public setActive(active: boolean): void {
        this.active = active;
    }
}
